/**
 * @author Farah
 * main.js is serving the purpose for connecting
 * the logic with the index.php page
 * and hold utility functions
 */

//TODO LATITUDE to be set later
var LATITUDE = 40.3745615030193;

//TODO LONGITUDE to be set later
var LONGITUDE = -90.11803936751632;

//global varible for map
var map = null;

// cuerrnt position on the map as per the application user's existance on earth
var currPositon = null;

// Picked position to be set in the database
var pickedHomePosition = null;

//Home icon
var homeIcon = "https://google-maps-icons.googlecode.com/files/home.png";

//Home Position
var homePos = null;

//Todo: save fence radius in db
//Fence radius
var fenceRadius = 20;

//Dog position
var dogPos = null;

// load version 3 of the Google Maps API
google.load("maps", "3", {
	other_params : "sensor=false"
});

$(document).ready(function() {
	//console.log( "Before getCurrentLocationForPetAmigo !" );
	//console.log("Document ready !");

	//Load all the relevant coords for the map
	instantiateHomeOnMap();

	//Centers the map to the current location
	getCurrentLocationForPetAmigo();
	//Load the google map
	loadGoogleMap();

});

/**
 * Loads map with the help of google API
 */
function loadGoogleMap() {

	// embed 2D map in DOM

	map = new google.maps.Map($("#map").get(0), {
		center : currPositon,
		disableDefaultUI : true,
		mapTypeId : google.maps.MapTypeId.ROADMAP,
		scrollwheel : false,
		zoom : 17,
		zoomControl : true
	});
}

/**
 * Get current geolocation for home frm google map api
 * assumption application will be opened in home for the first time.
 */
function getCurrentLocationForPetAmigo() {

	if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {
			currPositon = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);

			//set the center og the map with respect to where u r on earth
			map.setCenter(currPositon);

		}, function() {
			//everything above goes well then following will execute
			handleNoGeolocation(true);
		});
	} else {
		// Browser doesn't support Geolocation
		handleNoGeolocation(false);
	}
}

/**
 * Healper function for getCurrentLocationForPetAmigo()
 * @param {Object} errorFlag is passed as bool value from calling function
 */
function handleNoGeolocation(errorFlag) {
	if (errorFlag) {
		var content = 'Error: The Geolocation service failed.';
	} else {
		var content = 'Error: Your browser doesn\'t support geolocation.';
	}
}

/**
 * Place the marker (baloon) on the map
 * its a healper function called from pickHomeOnMap()
 * @param {Object} position
 * @param {Object} map
 */
function placeMarker(position, map) {
	var marker = new google.maps.Marker({
		position : position,
		map : map
	});
	// console.log("Inside Placemarker" + position.lat());

	$("#placeOnMap").val(position.lat());
	$("#placeOnMap").val(position.lng());

	map.panTo(position);
}

/**
 * Pick home with google mark on map API
 */
function pickHomeOnMap() {
	// adding event listner to Map.click()
	google.maps.event.addDomListener(map, 'click', function(e) {
		// This function is to mark baloon on the map
		//placeMarker(e.latLng, map);

		//setting global variable value for var pickedHomePosition to store in database
		homePos = e.latLng;

		var lat = homePos.lat();
		var lng = homePos.lng();

		$("#lat").val(lat);
		//var selectedLat = ($("#placeOnMap").val());
		$("#lng").val(lng);
		
		
		
		//saving user picked position in db
		$.ajax({
			type : "POST",
			url : "php/InsertHome.php",
			data : {
				lat : lat,
				lng : lng
			}

		}).done(function() {
			
			displayIconOnMap(homeIcon, homePos);
			//TODO : Modify modal dialog to ask user to reload page 
			
			//console.log("Onclick House "+house.position.lat());
		});
	});
}

/**
 * instantiate Home on map
 */
function instantiateHomeOnMap() {
	console.log('Inside instantiateHomeOnMap before');

	//var isHomeFound = isHomeInDB();

	// initialize House propertiy
	var homeConfig = {
		name : "Home",
		position : null
	}

	house = new Houses(homeConfig);
	//Looking for Home location in DB
	house.getHomeLocationFromDB(homeIcon, house);
	//isHomeInDB();

	console.log('Inside instantiateHomeOnMap After');

	$(document).ajaxStop(function() {
		console.log('Inside Ajaxstop' + isHomeFound);

		if (!isHomeFound) {
			//TODO: Display modal window asking end-user to pick home location from map
			//Use Bootstrap or jqueryUI
			//Display the modal dialog for picking home
			//The pickHomeOnMap has been called from the dialog
			displayModal();

			//centers the map to the current location
			getCurrentLocationForPetAmigo();

			//Should be only called if home location not present in Db
			// $("#pickHome").click(function() {
			// pickHomeOnMap();
			// });

		} else {

			//Disable pickhome dilog
			$('#pickHomeDiv').hide();

			//home found in DB place the marker
			displayIconOnMap(homeIcon, homePos);

			if (isHomeFound) {
				console.log("Yes");
			} else {
				console.log("No");
			}
		}
		
		//creating fence around house
		var fenceOptions = {
			radius: fenceRadius
		};
		var myfence = new fence(fenceOptions);
		myfence.createFence();
		
		
		//Creating a dog object 
		var dogOptions = {
			position: homePos
		};
		//Displaying dog marker on map
		var myDog = new dog(dogOptions);
		myDog.showDogOnMap();
		
	});

	//new google.maps.LatLng(residenceData.lat, residenceData.lng);
}